<template>
  <!-- <Dialog v-model="dialogVisible" title="自定义显示视图" width="70%"> -->
  <div class="transfer-container">
    <div class="transfer-panel">
      <div class="header">
        <h3>请选择列表中要展示的字段</h3>
        <div class="header-all">
          <input type="checkbox" id="left-item-all" v-model="isAllSelected" />
          <label :for="'left-item-all'">全选</label>
        </div>
      </div>
      <div class="transfer-list">
        <div
          v-for="item in leftList"
          :key="item.id"
          class="transfer-items"
          draggable="true"
          @dragstart="handleDragStart($event, item)"
        >
          <input
            type="checkbox"
            :id="'left-item-' + item.prop"
            :value="item.prop"
            v-model="selectedLeftItems"
          />
          <label :for="'left-item-' + item.prop">{{ item.label }}</label>
        </div>
      </div>
    </div>

    <div class="transfer-actions">
      <el-button
        @click="moveSelectedToRight"
        style="width: 50px; color: #fff; background-color: #3991f9"
        >{{ '>' }}</el-button
      >
      <!-- <button @click="moveAllToRight">→→→</button>
        <button @click="moveAllToLeft">←←←</button> -->
      <!-- <el-button @click="moveSelectedToLeft" style="width:50px;color:#fff;background-color:#3991f9">{{'<'}}</el-button> -->
    </div>

    <div class="transfer-panel">
      <div class="header">
        <h3>请选择列表中要展示的字段</h3>
        <span class="header-clear" @click="handleClear"> 清空</span>
      </div>
      <div class="transfer-list" ref="rightListRef">
        <div v-for="item in rightList" :key="item.prop" class="transfer-item">
          <div class="transfer-item-li">
            <span>
              {{ item.label }}
            </span>
            <div>
              <span style="display: contents; font-size: 20px; color: red; cursor: pointer">
                <el-icon>
                  <Delete @click="handleDeleteicon(item)" />
                </el-icon>
              </span>
              <span style="display: contents; font-size: 20px; cursor: move">
                <el-icon style="margin-left: 10px">
                  <Rank />
                </el-icon>
              </span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
  <!-- <template #footer>
        <el-button @click="saveVisible = true" style="width: 58px">取 消</el-button>
        <el-button
          :disabled="formLoading"
          @click="submitForm"
          style="width: 58px; color: #fff; background-color: #3991f9"
          >确 定</el-button
        >
      </template> -->
</template>

<script lang="ts" setup>
  import { ref, nextTick } from 'vue'
  import Sortable from 'sortablejs'
  import { Delete, Rank } from '@element-plus/icons-vue'
  import { ElMessage } from 'element-plus'

  const dialogVisible = ref(false) // 弹窗的是否展示
  const saveVisible = ref(false) // 弹窗的是否展示
  const schemeName = ref('') //方案名称
  const formLoading = ref(false)

  defineOptions({ name: 'TransferTable' })
  // 暂存初始值
  const leftList: any = ref([
    {
      label: 'option1',
      prop: 'key1'
    },
    {
      label: 'option2',
      prop: 'key2'
    },
    {
      label: 'option3',
      prop: 'key3'
    },
    {
      label: 'option4',
      prop: 'key4'
    },
    {
      label: 'option5',
      prop: 'key5'
    }
  ])

  // 源列表数据
  //   const leftList: any = ref([]);

  // 目标列表数据
  const rightList: any = ref([])

  // 左边选中的项
  const selectedLeftItems = ref<number[]>([])

  /** 打开弹窗 */
  const open = () => {
    leftList.value = props.dataList
    saveList.value = props.dataList
    dialogVisible.value = true
    restForm()
    initSortable()
  }
  const props = defineProps({
    dataList: { type: Array, default: () => [] }
  })

  defineExpose({ open }) // 提供 open 方法，用于打开弹窗

  const emits = defineEmits(['confirm']) //定义事件

  // 将选中的数据从源列表移动到目标列表
  const moveSelectedToRight = () => {
    let selectedItems = leftList.value.filter((item) => selectedLeftItems.value.includes(item.prop))
    rightList.value.push(...selectedItems)
    leftList.value = leftList.value.filter((item) => !selectedLeftItems.value.includes(item.prop))
    // console.log("rightList",leftList.value);
    selectedLeftItems.value = []
  }

  // 拖拽开始事件
  const handleDragStart = (e: DragEvent, item: any) => {
    if (e.dataTransfer) {
      e.dataTransfer.setData('text/plain', JSON.stringify(item))
    }
  }

  // 初始化右边列表的拖拽排序
  const rightListRef = ref<HTMLElement | null>(null)

  //重置
  const restForm = () => {
    rightList.value = []
    selectedLeftItems.value = []
    schemeName.value = ''
  }

  //拖拽
  const initSortable = () => {
    nextTick(() => {
      // console.log("DOM 元素已获取:", rightListRef);
      if (rightListRef.value) {
        new Sortable(rightListRef.value, {
          animation: 150,
          ghostClass: 'sortable-ghost',
          onEnd: (evt: any) => {
            const oldIndex = evt.oldIndex
            const newIndex = evt.newIndex
            const item = rightList.value[oldIndex]
            rightList.value.splice(oldIndex, 1)
            rightList.value.splice(newIndex, 0, item)
          }
        })
      } else {
        // console.log("DOM 元素未获取:");
      }
    })
  }

  //点击确认之后
  const submitForm = () => {
    if (rightList.value && rightList.value.length !== 0) {
      saveVisible.value = true
    } else {
      ElMessage.error('请选择需要显示的字段！')
    }
  }

  //保存方案
  const submitFormSave = () => {
    if (schemeName.value) {
      emits('confirm', rightList.value)
      rightList.value = []
      selectedLeftItems.value = []
      dialogVisible.value = false
      saveVisible.value = false
    } else {
      ElMessage.error('请输入方案名！')
    }
  }
  //点击右侧清空
  const handleClear = () => {
    rightList.value = []
    leftList.value = saveList.value
  }

  // 单条选择删除
  const handleDeleteicon = (value) => {
    rightList.value = rightList.value.filter((item) => item !== value)
    leftList.value.push(value)
  }

  // 计算属性，判断是否全选
  const isAllSelected = computed({
    get: () => {
      // 如果选中的子项数量等于所有子项的数量，则全选
      return selectedLeftItems.value.length === leftList.value.length
    },
    set: (value) => {
      // 如果全选复选框被选中，则将所有子项添加到选中数组中
      if (value) {
        selectedLeftItems.value = leftList.value.map((item) => item.prop)
      } else {
        // 如果全选复选框被取消选中，则清空选中数组
        selectedLeftItems.value = []
      }
    }
  })
  onMounted(() => {
    restForm()
    initSortable()
  })
</script>

<style scoped lang="scss">
  .saveContent {
    display: flex;
    align-items: center;

    > span {
      margin-right: 17px;
      font-family: PingFangSC, 'PingFang SC';
      font-size: 14px;
      font-style: normal;
      font-weight: 500;
      line-height: 20px;
      color: #1a3056;
      text-align: right;
    }
  }

  .transfer-container {
    display: flex;
    justify-content: space-between;
    width: 100%;
  }

  .transfer-panel {
    width: 45%;
    border: 1px solid #dcdfe6;
    border-radius: 4px;

    .header {
      display: flex;
      width: 100%;
      min-height: 37px;
      padding-left: 8px;
      background: #eef0f4;
      align-items: center;

      h3 {
        font-family: PingFangSC, 'PingFang SC';
        font-size: 15px;
        font-style: normal;
        font-weight: 600;
        line-height: 22px;
        color: #1a3056;
        text-align: center;
      }

      .header-clear {
        display: flex;
        width: 32px;
        height: 22px;
        margin-left: 12px;
        font-family: PingFangSC, 'PingFang SC';
        font-size: 16px;
        font-style: normal;
        font-weight: 500;
        line-height: 22px;
        color: #3991f9;
        text-align: right;
        cursor: pointer;
      }

      .header-all {
        // cursor: pointer
        display: flex;
        margin-left: 12px;
        font-family: PingFangSC, 'PingFang SC';
        font-size: 16px;
        font-style: normal;
        font-weight: 400;
        line-height: 22px;
        color: #3991f9;
        text-align: left;
      }

      .header-all input[type='checkbox'] {
        margin-right: 6px;
      }
    }
  }

  .transfer-list {
    min-height: 200px;
    padding: 10px;
    margin-top: 10px;
  }

  .transfer-item {
    display: flex;
    width: 100%;
    padding: 5px;
    margin: 5px 0;
    cursor: grab;
    background-color: #f9f9f9;
    align-items: center;

    .transfer-item-li {
      display: flex;
      width: 100%;
      justify-content: space-between;
      align-items: center;
    }
  }

  .transfer-items {
    display: flex;
    padding: 5px;
    margin: 5px 0;
    background-color: #f9f9f9;
    align-items: center;
  }

  .transfer-items input[type='checkbox'] {
    margin-right: 10px;
  }

  .transfer-actions {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    width: 10%;
  }

  button {
    padding: 5px;
    margin: 5px 0;
    cursor: pointer;
  }

  .sortable-ghost {
    background: #c8ebfb;
    opacity: 0.5;
  }

  :deep(.el-button + .el-button) {
    margin: 0;
  }
</style>
